package com.bawei.module_goods.ui

import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.lib_common.mvi.base.BaseMVIActivity
import com.bawei.module_goods.R
import com.bawei.module_goods.databinding.ActivityGoodsDetailBinding
import com.bawei.module_goods.intent.GoodsDetailIntent
import com.bawei.module_goods.state.GoodsState
import com.bawei.module_goods.viewmodel.GoodsDetailViewModel
import kotlinx.coroutines.launch
import com.bawei.module_goods.adapter.DetailBannerAdapter
import com.bumptech.glide.Glide
import com.youth.banner.listener.OnPageChangeListener
import android.graphics.Paint
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.widget.ImageView
import com.bawei.module_goods.entity.DetailEntity
import com.google.gson.reflect.TypeToken
import com.google.gson.Gson
import com.bawei.module_goods.entity.SpecAttr
import com.bawei.module_goods.network.GoodsApi
import com.bawei.lib_net.RetrofitFactory
import android.util.Log
import android.widget.LinearLayout
import android.content.Intent
import android.widget.TextView
import androidx.lifecycle.LifecycleObserver
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.module_goods.adapter.CommentAdapter
import com.bawei.module_goods.entity.CommentEntity
import com.bawei.module_goods.entity.ShoppingCartDisplayItem

/*
* 商品详情页面
* */
class GoodsDetailActivity : BaseMVIActivity() {
    private lateinit var binding : ActivityGoodsDetailBinding
    private lateinit var viewModel: GoodsDetailViewModel
    
    // 从Intent中获取商品ID
    private val goodsId: Int by lazy {
        intent.getIntExtra("goods_id", -1)
    }

    private var isFavorite = false // 本地收藏状态
    private var bannerAdapter: DetailBannerAdapter? = null
    private var detailEntityRef: DetailEntity? = null

    override fun generateViewModel() {
        viewModel = ViewModelProvider(this)[GoodsDetailViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        binding = ActivityGoodsDetailBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        // 顶部返回按钮
        binding.ivBack.setOnClickListener { finish() }
        // 顶部分享按钮
        binding.ivShare.setOnClickListener { showToast("分享功能待实现") }
        // Tab切换
        val tabs = listOf(binding.tvTabGoods, binding.tvTabComment, binding.tvTabDetail)
        val anchors = listOf(
            binding.root.findViewById<View>(R.id.anchorGoods),
            binding.ivComment, // 评价分割线TextView，id为ivComment
            binding.ivDetail // 详情分割线TextView，id为ivDetail
        )
        Log.d("TabDebug", "anchors.size=${anchors.size}, ivDetail is null? ${binding.ivDetail == null}")
        tabs.forEachIndexed { idx, tv ->
            tv.setOnClickListener {
                tabs.forEachIndexed { i, t ->
                    t.setTextColor(if (i == idx) getColor(R.color.colorPrimary) else 0xFF222222.toInt())
                    t.setTypeface(null, if (i == idx) android.graphics.Typeface.BOLD else android.graphics.Typeface.NORMAL)
                }
                binding.scrollView.post {
                    if (idx == 2) {
                        val location = IntArray(2)
                        binding.ivDetail.getLocationInWindow(location)
                        val scrollViewLocation = IntArray(2)
                        binding.scrollView.getLocationInWindow(scrollViewLocation)
                        val offset = location[1] - scrollViewLocation[1] - binding.layoutTopBar.height
                        Log.d("TabDebug", "ivDetail windowY=${location[1]}, scrollView windowY=${scrollViewLocation[1]}, offset=$offset")
                        binding.scrollView.post {
                            binding.scrollView.smoothScrollBy(0, offset)
                        }
                    }else {
                            Log.d("TabDebug", "anchors[$idx].top=${anchors[idx].top}")
                            binding.scrollView.smoothScrollTo(0, anchors[idx].top)
                    }
                }
            }
        }
        // 滚动监听切换tab高亮
        binding.scrollView.setOnScrollChangeListener { _, _, _, _, _ ->
            val topBarHeight = binding.layoutTopBar.height
            val anchors = listOf(
                binding.root.findViewById<View>(R.id.anchorGoods),
                binding.ivComment,
                binding.ivDetail
            )
            val tabs = listOf(binding.tvTabGoods, binding.tvTabComment, binding.tvTabDetail)
            // 计算每个锚点距离顶部栏下方的距离
            val distances = anchors.map { anchor ->
                val location = IntArray(2)
                anchor.getLocationInWindow(location)
                location[1] - topBarHeight
            }
            // 找到距离顶部栏最近且>=0的区块
            val current = distances.indexOfFirst { it >= 0 }
                .let { if (it == -1) distances.lastIndex else it }
            tabs.forEachIndexed { i, t ->
                t.setTextColor(if (i == current) getColor(R.color.colorPrimary) else 0xFF222222.toInt())
                t.setTypeface(null, if (i == current) android.graphics.Typeface.BOLD else android.graphics.Typeface.NORMAL)
            }
        }
        // 底部购物车跳转
        binding.root.findViewById<View>(R.id.llCart)?.setOnClickListener {
            startActivity(Intent(this, ShoppingCartActivity::class.java))
        }
        // 设置返回按钮点击事件
        binding.ivBack.setOnClickListener {
            finish()
        }
        // 收藏按钮点击事件
        binding.ivFavorite.setOnClickListener {
            isFavorite = !isFavorite
            updateFavoriteUI()
        }
        binding.tvParams.setOnClickListener {
            val detailEntity = detailEntityRef
            val sb = StringBuilder()
            if (!detailEntity?.params.isNullOrBlank()) {
                sb.append(detailEntity?.params)
            }
            val specListJson = Gson().toJson(detailEntity?.specAttrList)
            val specList: List<SpecAttr> = try {
                Gson().fromJson(specListJson, object : TypeToken<List<SpecAttr>>() {}.type)
            } catch (e: Exception) {
                emptyList()
            }
            specList.forEach { spec ->
                if (!spec.attrKey.isNullOrBlank()) {
                    sb.append("\n\n").append(spec.attrKey).append(": ")
                }
                val values = spec.goodsAttrValues?.joinToString(", ") { it.attrValue ?: "" }
                if (!values.isNullOrBlank()) {
                    sb.append(values)
                }
            }
            val dialog = ParamDialog("产品参数", sb.toString().trim())
            dialog.show(supportFragmentManager, "ParamDialog")
        }
    }

    override fun initData() {
        super.initData()
        // 检查商品ID是否有效
        if (goodsId == -1) {
            showError("商品ID无效")
            return
        }
        // 自动添加足迹
        addFootPrint(goodsId)
        // 加载商品详情数据
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.intents.send(GoodsDetailIntent.DetailIntent(goodsId))
            }
        }
        //发送评论请求
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.intents.send(GoodsDetailIntent.DetailCommentIntent(goodsId,0,3))
            }
        }
    }


    private fun addFootPrint(goodsId: Int) {
        lifecycleScope.launch {
            try {
                val api = RetrofitFactory.getRetrofitFactory().create(GoodsApi::class.java)
                val response = api.addFootPrint(goodsId)
                if (response.code == 200) {
                    Log.d("FootPrint", "足迹添加成功")
                } else {
                    Log.e("FootPrint", "足迹添加失败: ${response.msg}")
                }
            } catch (e: Exception) {
                Log.e("FootPrint", "足迹添加异常: ${e.message}", e)
            }
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.goodsDetailStateFlow.collect { state ->
                    when (state) {
                        GoodsState.Empty -> {
                            showEmpty()
                        }
                        GoodsState.Init -> {
                            showLoading()
                        }
                        is GoodsState.onFailed -> {
                            hideLoading()
                            showError(state.msg)
                        }
                        is GoodsState.onSuccess -> {
                            hideLoading()
                            when (state.type) {
                                "detail" -> {
                                    val detailEntity = state.data as? DetailEntity
                                    if (detailEntity != null) {
                                        updateUI(detailEntity)
                                    } else {
                                        showError("数据格式错误")
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(androidx.lifecycle.Lifecycle.State.STARTED) {
                viewModel.goodsDetailCommentStateFlow.collect{
                    when (it) {
                        GoodsState.Empty -> {}
                        GoodsState.Init -> {}
                        is GoodsState.onFailed -> {
                            Log.d("DetailImageAdapter", "loadComments: ${it.msg}")
                        }
                        is GoodsState.onSuccess -> {
                            val comments = it.data as CommentEntity
                            if (comments.records.isNotEmpty()) {
                                binding.rvComments.adapter = CommentAdapter(comments.records)
                                binding.rvComments.layoutManager = LinearLayoutManager(this@GoodsDetailActivity)

                            } else {
                                binding.rvComments.visibility = View.GONE
                                binding.rvComments.visibility = View.GONE
                            }
                        }
                    }
                }
            }
        }
    }
    // 轮播图图片解析，终极Any兼容
    private fun parsePosterUll(rawList: List<String>?): List<String> {
        if (rawList.isNullOrEmpty()) return emptyList()
        // 合并所有字符串为一个大字符串
        val merged = rawList.joinToString(separator = "")
        // 用正则提取所有http开头的图片链接
        val regex = "https?://[\\w./%-]+\\.(jpg|jpeg|png|gif)".toRegex(RegexOption.IGNORE_CASE)
        val result = regex.findAll(merged).map { it.value.trim() }.toList()
        android.util.Log.d("GoodsDetail", "posterUll merged = $merged, result = $result")
        return result
    }
    // 详情图片解析，终极Any兼容anchors
    private fun parseDetailImages(rawList: List<String>?): List<String> {
        if (rawList.isNullOrEmpty()) return emptyList()
        val regex = "https?://[\\w./%-]+\\.(jpg|jpeg|png|gif)".toRegex(RegexOption.IGNORE_CASE)
        val result = mutableListOf<String>()
        for (item in rawList) {
            regex.findAll(item).forEach { matchResult ->
                result.add(matchResult.value.trim())
            }
        }
        return result
    }
    private fun updateUI(detailEntity: DetailEntity) {
        // 打印原始数据，便于调试
        android.util.Log.d("RawPosterUll", "posterUll=${detailEntity.posterUll}")
        android.util.Log.d("RawDetailUrl", "detailUrl=${detailEntity.detailUrl}")
        detailEntityRef = detailEntity
        // 轮播图
        val bannerList = parsePosterUll(detailEntity.posterUll)
        android.util.Log.d("BannerDebug", "bannerList size=${bannerList.size}, $bannerList")
        if (bannerList.isNotEmpty()) {
            bannerAdapter = DetailBannerAdapter(bannerList)
            binding.vpBanner.setAdapter(bannerAdapter)
            binding.vpBanner.isAutoLoop(true)
            binding.vpBanner.start()
            // 指示器
            binding.tvBannerIndicator.text = "1/${bannerList.size}"
            binding.vpBanner.addOnPageChangeListener(object : OnPageChangeListener {
                override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
                override fun onPageSelected(position: Int) {
                    binding.tvBannerIndicator.text = "${position + 1}/${bannerList.size}"
                }
                override fun onPageScrollStateChanged(state: Int) {}
            })
        }
        // 详情图片展示（方法二：LinearLayout动态addView）
        val detailImages = parseDetailImages(detailEntity.detailUrl)
        val llDetailImages = binding.root.findViewById<LinearLayout>(R.id.llDetailImages)
        llDetailImages.removeAllViews()
        for (imgUrl in detailImages) {
            val imageView = ImageView(this)
            val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            params.topMargin = 12 // px，如需dp可用TypedValue.applyDimension
            imageView.layoutParams = params
            imageView.adjustViewBounds = true
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            Glide.with(this).load(imgUrl).into(imageView)
            llDetailImages.addView(imageView)
        }
        // 主图
        Glide.with(this).load(detailEntity.mainImgUrl).placeholder(R.drawable.bg_ad_placeholder).into(binding.ivAd)
        // 标题
        binding.tvTitle.text = detailEntity.title ?: ""
        // 价格
        binding.tvPrice.text = "¥${detailEntity.purchasePrice ?: "--"}"
        binding.tvMarketPrice.text = if (detailEntity.marketPriceFee != null) "¥${detailEntity.marketPriceFee}" else ""
        binding.tvMarketPrice.paintFlags = binding.tvMarketPrice.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        // 保障
        binding.tvGuarantee.text = "售后无忧·包邮"
        // 收藏UI
        updateFavoriteUI()
        // 购买按钮
        binding.btnBuy.setOnClickListener {
            val skuList = (detailEntity.skuList ?: emptyList())
            android.util.Log.d("SkuDebug", "skuList=$skuList")
            val dialog = SkuSelectDialog(
                skuList,
                detailEntity.mainImgUrl,
                detailEntity.purchasePrice?.toInt(),
                detailEntity.code
            ) { model, quantity ->
                // 立即购买跳转订单
                val selectedSku = skuList.find { it.skuName == model }
                val skuId = selectedSku?.id
                val skuCode = selectedSku?.skuCode
                val item = ShoppingCartDisplayItem(
                    cartId = 0,
                    goodsId = detailEntity.id ?: 0,
                    goodsSkuId = skuId,
                    number = quantity,
                    goodsName = detailEntity.title,
                    goodsImage = detailEntity.mainImgUrl,
                    price = detailEntity.purchasePrice?.toDouble()
                )
                val json = Gson().toJson(listOf(item))
                com.alibaba.android.arouter.launcher.ARouter.getInstance()
                    .build("/module_mine/ConfirmOrderActivity")
                    .withString("cartItemsJson", json)
                    .navigation(this)
            }
            dialog.show(supportFragmentManager, "SkuSelectDialog")
        }
//        // 预约试驾（底部左侧）
//        binding.root.findViewById<View>(R.id.bottom_bar)?.findViewById<View>(R.id.)?.setOnClickListener {
//            showToast("预约试驾功能待实现")
//        }
        // 参数（只显示一部分，超出省略）
        val paramsText = detailEntity.params ?: ""
        binding.tvParams.text = if (paramsText.length > 20) paramsText.substring(0, 20) + "..." else paramsText
    }
    
    private fun updateFavoriteUI() {
        if (isFavorite) {
            binding.ivFavorite.setImageResource(R.drawable.ic_favorite_filled)
            binding.tvFavorite.text = "已收藏"
        } else {
            binding.ivFavorite.setImageResource(R.drawable.ic_favorite_border)
            binding.tvFavorite.text = "收藏"
        }
    }
    
    private fun showLoading() {
        binding.scrollView.visibility = View.GONE
        binding.tvEmpty.visibility = View.GONE
        binding.tvError.visibility = View.GONE
    }
    
    private fun hideLoading() {
        binding.scrollView.visibility = View.VISIBLE
        binding.tvEmpty.visibility = View.GONE
        binding.tvError.visibility = View.GONE
    }
    
    private fun showEmpty() {
        binding.scrollView.visibility = View.GONE
        binding.tvEmpty.visibility = View.VISIBLE
        binding.tvError.visibility = View.GONE
    }
    
    private fun showError(message: String) {
        binding.scrollView.visibility = View.GONE
        binding.tvEmpty.visibility = View.GONE
        binding.tvError.visibility = View.VISIBLE
        binding.tvError.text = message
    }
    
    private fun showToast(message: String) {
        // 这里可以使用Toast或其他提示方式
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
    }

    private fun loadComments() {

    }
}

class DetailImageAdapter(private val images: List<String>) : RecyclerView.Adapter<DetailImageAdapter.ImageViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val imageView = ImageView(parent.context)
        imageView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        imageView.adjustViewBounds = true // 保证高度自适应
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP // 宽度占满
        return ImageViewHolder(imageView)
    }

    override fun getItemCount() : Int{
        return images.size
    }
    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        Glide.with(holder.imageView.context).load(images[position]).into(holder.imageView)
    }
    class ImageViewHolder(val imageView: ImageView) : RecyclerView.ViewHolder(imageView)
}